package com.changgou.goods.service.impl;

import com.alibaba.fastjson.JSON;
import com.changgou.entity.Constants;
import com.changgou.goods.dao.*;
import com.changgou.goods.pojo.*;
import com.changgou.goods.service.SpuService;
import com.changgou.util.IdWorker;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import org.apache.commons.lang.StringUtils;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import tk.mybatis.mapper.entity.Example;

import java.util.Date;
import java.util.List;
import java.util.Map;

@Service
public class SpuServiceImpl implements SpuService {

    @Autowired
    private SpuMapper spuMapper;

    @Autowired
    private SkuMapper skuMapper;

    @Autowired
    private BrandMapper brandMapper;

    @Autowired
    private CategoryMapper categoryMapper;
    
    @Autowired
    private CategoryBrandMapper categoryBrandMapper;

    @Autowired
    private IdWorker idWorker;

    @Autowired
    private RabbitTemplate rabbitTemplate;


    /**
     * 查询全部列表
     * @return
     */
    @Override
    public List<Spu> findAll() {
        return spuMapper.selectAll();
    }

    /**
     * 根据ID查询
     * @param id
     * @return
     */
    @Override
    public Spu findById(String id){
        return  spuMapper.selectByPrimaryKey(id);
    }


    /**
     * 增加
     * @param spu
     */
    @Override
    public void add(Spu spu){
        spuMapper.insert(spu);
    }


    /**
     * 修改
     * @param spu
     */
    @Override
    public void update(Spu spu){
        spuMapper.updateByPrimaryKey(spu);
    }

    /**
     * 删除
     * @param id
     */
    @Override
    public void delete(String id){
        spuMapper.deleteByPrimaryKey(id);
    }


    /**
     * 条件查询
     * @param searchMap
     * @return
     */
    @Override
    public List<Spu> findList(Map<String, Object> searchMap){
        Example example = createExample(searchMap);
        return spuMapper.selectByExample(example);
    }

    /**
     * 分页查询
     * @param page
     * @param size
     * @return
     */
    @Override
    public Page<Spu> findPage(int page, int size){
        PageHelper.startPage(page,size);
        return (Page<Spu>)spuMapper.selectAll();
    }

    /**
     * 条件+分页查询
     * @param searchMap 查询条件
     * @param page 页码
     * @param size 页大小
     * @return 分页结果
     */
    @Override
    public Page<Spu> findPage(Map<String,Object> searchMap, int page, int size){
        PageHelper.startPage(page,size);
        Example example = createExample(searchMap);
        return (Page<Spu>)spuMapper.selectByExample(example);
    }

    /**
     * 构建查询对象
     * @param searchMap
     * @return
     */
    private Example createExample(Map<String, Object> searchMap){
        Example example=new Example(Spu.class);
        Example.Criteria criteria = example.createCriteria();
        if(searchMap!=null){
            // 主键
            if(searchMap.get("id")!=null && !"".equals(searchMap.get("id"))){
                criteria.andEqualTo("id",searchMap.get("id"));
           	}
            // 货号
            if(searchMap.get("sn")!=null && !"".equals(searchMap.get("sn"))){
                criteria.andEqualTo("sn",searchMap.get("sn"));
           	}
            // SPU名
            if(searchMap.get("name")!=null && !"".equals(searchMap.get("name"))){
                criteria.andLike("name","%"+searchMap.get("name")+"%");
           	}
            // 副标题
            if(searchMap.get("caption")!=null && !"".equals(searchMap.get("caption"))){
                criteria.andLike("caption","%"+searchMap.get("caption")+"%");
           	}
            // 图片
            if(searchMap.get("image")!=null && !"".equals(searchMap.get("image"))){
                criteria.andLike("image","%"+searchMap.get("image")+"%");
           	}
            // 图片列表
            if(searchMap.get("images")!=null && !"".equals(searchMap.get("images"))){
                criteria.andLike("images","%"+searchMap.get("images")+"%");
           	}
            // 售后服务
            if(searchMap.get("saleService")!=null && !"".equals(searchMap.get("saleService"))){
                criteria.andLike("saleService","%"+searchMap.get("saleService")+"%");
           	}
            // 介绍
            if(searchMap.get("introduction")!=null && !"".equals(searchMap.get("introduction"))){
                criteria.andLike("introduction","%"+searchMap.get("introduction")+"%");
           	}
            // 规格列表
            if(searchMap.get("specItems")!=null && !"".equals(searchMap.get("specItems"))){
                criteria.andLike("specItems","%"+searchMap.get("specItems")+"%");
           	}
            // 参数列表
            if(searchMap.get("paraItems")!=null && !"".equals(searchMap.get("paraItems"))){
                criteria.andLike("paraItems","%"+searchMap.get("paraItems")+"%");
           	}
            // 是否上架
            if(searchMap.get("isMarketable")!=null && !"".equals(searchMap.get("isMarketable"))){
                criteria.andEqualTo("isMarketable",searchMap.get("isMarketable"));
           	}
            // 是否启用规格
            if(searchMap.get("isEnableSpec")!=null && !"".equals(searchMap.get("isEnableSpec"))){
                criteria.andEqualTo("isEnableSpec", searchMap.get("isEnableSpec"));
           	}
            // 是否删除
            if(searchMap.get("isDelete")!=null && !"".equals(searchMap.get("isDelete"))){
                criteria.andEqualTo("isDelete",searchMap.get("isDelete"));
           	}
            // 审核状态
            if(searchMap.get("status")!=null && !"".equals(searchMap.get("status"))){
                criteria.andEqualTo("status",searchMap.get("status"));
           	}

            // 品牌ID
            if(searchMap.get("brandId")!=null ){
                criteria.andEqualTo("brandId",searchMap.get("brandId"));
            }
            // 一级分类
            if(searchMap.get("category1Id")!=null ){
                criteria.andEqualTo("category1Id",searchMap.get("category1Id"));
            }
            // 二级分类
            if(searchMap.get("category2Id")!=null ){
                criteria.andEqualTo("category2Id",searchMap.get("category2Id"));
            }
            // 三级分类
            if(searchMap.get("category3Id")!=null ){
                criteria.andEqualTo("category3Id",searchMap.get("category3Id"));
            }
            // 模板ID
            if(searchMap.get("templateId")!=null ){
                criteria.andEqualTo("templateId",searchMap.get("templateId"));
            }
            // 运费模板id
            if(searchMap.get("freightId")!=null ){
                criteria.andEqualTo("freightId",searchMap.get("freightId"));
            }
            // 销量
            if(searchMap.get("saleNum")!=null ){
                criteria.andEqualTo("saleNum",searchMap.get("saleNum"));
            }
            // 评论数
            if(searchMap.get("commentNum")!=null ){
                criteria.andEqualTo("commentNum",searchMap.get("commentNum"));
            }

        }
        return example;
    }


    @Transactional
    @Override
    public void addGoods(Goods goods) {
        //1.保存spu数据
        goods.getSpu().setId(String.valueOf(idWorker.nextId())); //这里使用分布式ID代替表的自增主键ID
        spuMapper.insertSelective(goods.getSpu());

        //2.保存sku列表数据
        saveSkuList(goods);

    }

    private void saveSkuList(Goods goods) {
        //保存sku数据
        Spu spu = goods.getSpu();
        Integer brandId = spu.getBrandId();
        //根据ID查询品牌数据
        Brand brand = brandMapper.selectByPrimaryKey(brandId);

        Integer category3Id = spu.getCategory3Id();
        //根据三级分类ID查询分类数据
        Category category = categoryMapper.selectByPrimaryKey(category3Id);

        //处理分类与品牌的关联关系。如果brandId和categoryId在中间表不存在则插入。
        if(brand!=null && category!=null){
            CategoryBrand categoryBrand = new CategoryBrand();
            categoryBrand.setCategoryId(category3Id);
            categoryBrand.setBrandId(brandId);
            int count = categoryBrandMapper.selectCount(categoryBrand);//查询条数
            if(count==0){
                categoryBrandMapper.insertSelective(categoryBrand);//新增关联关系
            }
        }


        List<Sku> skuList = goods.getSkuList();
        if(skuList!=null && skuList.size()>0){
            for (Sku sku : skuList) {
                sku.setId(String.valueOf(idWorker.nextId()));//这里使用分布式ID代替表的自增主键ID
                sku.setCreateTime(new Date()); //创建时间
                sku.setUpdateTime(new Date()); //更新时间
                sku.setSpuId(spu.getId());
                if(StringUtils.isEmpty(sku.getSpec())){ //判断spec的值为空的情况下要特殊处理
                    sku.setSpec("{}");
                }
                Map<String,String> specMap = JSON.parseObject(sku.getSpec(), Map.class);
                String name = spu.getName();
                if(specMap.size()>0){
                    for(String key : specMap.keySet()){
                        String specVal = specMap.get(key);
                        name += " " + specVal;
                    }
                    sku.setName(name);//设置sku的名称
                }
                if(brand!=null){
                    sku.setBrandName(brand.getName()); //设置品牌名称
                }
                if(category!=null){
                    sku.setCategoryId(category3Id);//设置三级分类ID
                    sku.setCategoryName(category.getName());//设置三级分类的名称
                }

                skuMapper.insertSelective(sku);//新增sku数据

            }

        }
    }


    @Override
    public Goods findBySpuId(String spuId) {
        //根据spuId查询spu数据
        Spu spu = spuMapper.selectByPrimaryKey(spuId);

        //根据spuId查询sku的列表数据
        Example example = new Example(Sku.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("spuId", spuId);
        List<Sku> skuList = skuMapper.selectByExample(example);

        //封装商品数据
        Goods goods = new Goods();
        goods.setSpu(spu);
        goods.setSkuList(skuList);
        
        return goods;
    }

    @Transactional
    @Override
    public void updateGoods(Goods goods) {
        //1.更新spu数据
        spuMapper.updateByPrimaryKeySelective(goods.getSpu());

        //2.根据spuId删除库中所有的sku数据
        Example example = new Example(Sku.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("spuId", goods.getSpu().getId());
        skuMapper.deleteByExample(example);

        //3.新增sku数据
        saveSkuList(goods);
    }

    @Override
    public void auditGoods(String spuId) {
        //1.根据spuId查询spu
        Spu spu = spuMapper.selectByPrimaryKey(spuId);

        //2.设置审核状态为审核通过
        if(spu!=null){
            Spu updateSpu = new Spu();
            updateSpu.setStatus("1"); //0表示未审核、1表示审核通过
            updateSpu.setId(spuId);

            //3.执行更新 update tb_spu set status=1 where id=spuId
            spuMapper.updateByPrimaryKeySelective(updateSpu);
        }

    }


    @Override
    public void upGoods(String spuId) {
        //1.根据spuId查询商品
        Spu spu = spuMapper.selectByPrimaryKey(spuId);
        //2.设置spu状态为上架状态

        if(spu!=null){
            //前置条件判断：商品审核通过之后才能上架
            if("0".equals(spu.getStatus())){
                throw new RuntimeException("商品审核通过之后才能上架！");
            }
            Spu updateSpu = new Spu();
            updateSpu.setIsMarketable("1"); //设置为已上架
            updateSpu.setId(spuId);

            //3.执行更新
            spuMapper.updateByPrimaryKeySelective(updateSpu);

            //4.将spuId存入到mq中
            rabbitTemplate.convertAndSend(Constants.MQ_GOODS_UP_EXCHANGE, "", spuId);
        }
    }

    @Override
    public void downGoods(String spuId) {
        //1.根据spuId查询spu
        Spu spu = spuMapper.selectByPrimaryKey(spuId);
        //2.设置spu状态为已下架
        if(spu!=null) {

            //前置条件判断：判断当前商品是否是已下架，如果是则没必要再操作下架
            if ("0".equals(spu.getIsMarketable())) {
                throw new RuntimeException("已下架的商品无需操作下架");
            }

            //3.执行更新
            Spu updateSpu = new Spu();
            updateSpu.setId(spuId);
            updateSpu.setIsMarketable("0"); //设置状态为已下架
            spuMapper.updateByPrimaryKeySelective(updateSpu);

            //4.将spuId存入MQ中
            rabbitTemplate.convertAndSend(Constants.MQ_GOODS_DOWN_EXCHANGE, "", spuId);
        }

    }


    @Override
    public void logicDeleteGoods(String spuId) {
        //1.查询spu
        Spu spu = spuMapper.selectByPrimaryKey(spuId);

        //2.判断前置条件：判断商品的状态是否是已下架状态，只有已下架的商品才能删除
        if(spu!=null){
            if("1".equals(spu.getIsMarketable())){
                throw new RuntimeException("正在上架的商品不能删除！");
            }

            //3.设置为已删除状态
            Spu updateSpu = new Spu();
            updateSpu.setId(spuId);
            updateSpu.setIsDelete("1"); //设置为已删除

            //4.执行更新
            spuMapper.updateByPrimaryKeySelective(updateSpu);

        }


    }


    @Override
    public void restoreGoods(String spuId) {
        //1.查询spu
        Spu spu = spuMapper.selectByPrimaryKey(spuId);

        //2.判断前置条件：判断商品的状态是否是已删除，只有逻辑已删除的商品才能够恢复成功
        if(spu!=null){
            if("0".equals(spu.getIsDelete())){
                throw new RuntimeException("只有已经逻辑删除的商品才可以恢复！");
            }

            //3.设置为已恢复（正常）状态
            Spu updateSpu = new Spu();
            updateSpu.setId(spuId);
            updateSpu.setIsDelete("0"); //设置为已恢复

            //4.执行更新
            spuMapper.updateByPrimaryKeySelective(updateSpu);

        }
    }

    @Transactional
    @Override
    public void deleteGoods(String spuId) {
        //1.查询spu
        Spu spu = spuMapper.selectByPrimaryKey(spuId);

        //2.判断前置条件：判断商品的状态是否是已下架状态，只有已下架的商品才能删除

        if(spu!=null) {
            if ("1".equals(spu.getIsMarketable())) {
                throw new RuntimeException("正在上架的商品不能删除！");
            }
            //根据spuId删除spu
            spuMapper.deleteByPrimaryKey(spuId);

            //根据spuId删除sku
            Example example = new Example(Sku.class);
            Example.Criteria criteria = example.createCriteria();
            criteria.andEqualTo("spuId", spuId);
            skuMapper.deleteByExample(example); //delete from tb_sku where  spu_id =?
        }
    }
}
